package com.zdf.license.web.listener;

import com.zdf.license.core.model.LicenseExtraParam;
import com.zdf.license.verify.listener.ACustomVerifyListener;
import com.zdf.license.verify.listener.ParamType;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 当类注入到springboot中时候，初始化时自动将实例保存在了父类，
 * 每次启动校验父类都会调用 verify(LicenseExtraParam licenseExtra)
 */
@Component
public class Server1TimeVerifyListener extends ACustomVerifyListener {

    private Date server1Time=null;
    private static final ParamType paramType = new ParamType("Server1Time", "服务1有效时间", Date.class);

    @Override
    public void install(LicenseExtraParam licenseExtra) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            server1Time = dateFormat.parse(licenseExtra.getParams().get(paramType.getKey()).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void uninstall() {
        server1Time=null;
    }

    @Override
    public ParamType paramType() {
        return Server1TimeVerifyListener.paramType;
    }

    /**
     * 证书时间必须在当前时间之后，否则返回false
     */
    public boolean verify(){
        if (server1Time == null) {
            return Boolean.FALSE;
        }
        return server1Time.after(new Date());
    }
}
